from app.commons import Http
from app.setting import PER_PAGE


# 请求图书业务逻辑类
class YuShuBook(object):
    isbn_url = 'http://t.yushu.im/v2/book/isbn/{}'
    keyword_url = 'http://t.yushu.im/v2/book/search?q={}&count={}&start={}'

    def __init__(self):
        ''' 面向对象不是单纯的许多方法,而是特征+行为　明确这个类所要做的事情.'''
        self.total = 0
        self.books = []

    def search_by_isbn(self, isbn):
        # 构建url
        url = self.isbn_url.format(isbn)
        ret = Http.get(url)
        self.__fill_single(ret)

    def search_by_keyword(self, keyword, page=1):
        url = self.keyword_url.format(keyword, PER_PAGE, self.calculate_start(page))
        ret = Http.get(url)
        self.__fill_collection(ret)

    def __fill_single(self, data):
        if data:
            self.total = 1
            self.books.append(data)

    def __fill_collection(self, data):
        if data:
            self.total = data['total']
            self.books = data['books']

    @staticmethod
    def calculate_start(page):
        # 返回计算后的页数
        return (page-1) * PER_PAGE

    @property
    def first(self):
        return self.books[0] if self.total >= 1 else None